import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

///  StorageManager  缓存管理
class SharedPreStorage<T extends Object> {
  static late final SharedPreferences _pref;

  final String key;

  const SharedPreStorage(this.key);

  static Future<void> onInit() async {
    _pref = await SharedPreferences.getInstance();
  }

  /// 是否存在
  bool exist() {
    return _pref.containsKey(key);
  }

  /// 获取值
  T? get() {
    if (!exist()) {
      return null;
    }
    final value = _pref.getString(key);
    if (value != null) {
      try {
        return json.decode(value);
      } catch (e) {
        print('StorageManager T get() $value');
        return json.decode('$value');
      }
    } else {
      return null;
    }
  }

  /// 设置值
  Future<bool> set(T value) async {
    return _pref.setString(key, json.encode(value));
  }

  /// 移除key
  Future<bool> remove() {
    return _pref.remove(key);
  }
}
